<template>
  <div class="search-select-container" ref="containerRef">
    <!-- 搜索输入框 -->
    <el-input
      style="width:240px" :prefix-icon="Plus"
      v-model="searchQuery"
      :placeholder="placeholder || '请输入关键词搜索...'"
      @focus="handleFocus"
      @input="handleInput"
      @blur="handleBlur"
      clearable
      :class="{ 'active': isShowDropdown }"
    />
    <!-- 悬浮表格下拉框 -->
      <div class="dropdown-content" v-if="isShowDropdown && filteredData.length > 0">
        <!-- 表格展示数据 -->
        <el-table
          :data="filteredData"
          border header-cell-class-name="heardClassName"
          highlight-current-row
          height="200px"
          @row-click="handleRowClick"
          :max-height="maxHeight"
        >
          <!-- 动态渲染表格列 -->
          <el-table-column
            v-for="column in columns"
            :key="column.prop"
            
            :label="column.label"
            :width="column.width"
            :align="column.align || 'left'"
          >
            <template #default="scope">
              {{ scope.row[column.prop] || '0' }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 无数据提示 -->
        <div v-if="filteredData.length === 0" class="no-data">
          没有找到匹配的数据
        </div>
    </div>
    <!-- <el-popover
      v-model:visible="isShowDropdown"
      :virtual-triggering="true"
      :virtual-ref="containerRef"
      placement="bottom-start"
      :width="dropdownWidth"
      trigger="manual"
      @hide="handleDropdownHide"
    >
      <template #default>
      
      </template>
    </el-popover> -->
  </div>
</template>

<script setup >
import { ref, watch, nextTick, computed } from 'vue';
import { Plus } from '@element-plus/icons-vue';

import stores from '@/store';
//选择药品
const UnitTypeEnum = ref(stores.useBaseDataStore().getDictsSelect('UNIT'))
const DrugCategoryEnum = ref(stores.useBaseDataStore().getEnumSelect('drugCategoryEnum'))

// 组件属性
const props = defineProps({
  // 表格列配置
  columns: {
    type: Array,
    default: () => [],
    required: true
  },
  // 搜索框占位符
  placeholder: {
    type: String,
    default: '请输入关键词搜索...'
  },
  // 下拉框最大高度
  maxHeight: {
    type: Number,
    default: 300
  },
  // 搜索匹配的字段，默认匹配所有字段
  searchFields: {
    type: Array,
    default: null
  },
  storageId: {
    type: Number,
    default: null
  }
});

// 组件事件
const emit = defineEmits(['select', 'update:modelValue']);

// 响应式变量
const searchQuery = ref('');
const isShowDropdown = ref(false);
const containerRef = ref(null);
const dropdownWidth = ref('auto');
import { getDrugProfileList } from '@/api/drug'

const getDrugProfileListApi = async () => {
  let res = await getDrugProfileList({ pageNo: 1, pageSize: 9999, drugName: searchQuery.value, drugCategory: '', storageId: props.storageId })
  if (res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  }
  for (let index = 0; index < res.data.list.length; index++) {
      let item = res.data.list[index];
      if (item) {
          let minPackUnitText = item.minPackUnitText
          let packUnitText = item.packUnitText
            if (item.drugCategory == '1') {
              item.guige = item.drugDosage + '' + item.drugDosageUnitText + '*' + item.minPackQty + minPackUnitText + '/' + packUnitText

          }
          if (item.drugCategory == '2') {
              item.guige = '-'

          }
          if (item.drugCategory == '3') {
              item.guige = (item.minPackQty || '') + (minPackUnitText || '') + '/' + packUnitText

          }
      }
      for (let index2 = 0; index2 < DrugCategoryEnum.value.length; index2++) {
          let item2 = DrugCategoryEnum.value[index2];
          if (item && item.drugCategory == item2.value) {
              item.drugCategory = item2.text
          }
      }
  }
  filteredData.value = res.data.list
}
// 处理输入框获得焦点
const handleFocus = () => {
  nextTick(() => {
    isShowDropdown.value = true;
    // 设置下拉框宽度与输入框一致
    if (containerRef.value) {
      dropdownWidth.value = `${containerRef.value.offsetWidth}px`;
    }
  });
};

const filteredData = ref([]);
// 处理输入事件
const handleInput =  () => {
  // if (!isShowDropdown.value) {
  //   
  // }
  if(searchQuery.value != ''){
    isShowDropdown.value = true;
    getDrugProfileListApi()
  }else{
    isShowDropdown.value = false;
  }
};

// 处理输入框失去焦点
const handleBlur = () => {
  // 延迟关闭，以便处理点击事件
  //console.log('处理输入框失去焦点');
  setTimeout(() => {
    isShowDropdown.value = false;
  }, 200);
};


// 处理表格行点击
const handleRowClick = (row) => {
  // 选中数据后关闭下拉框

  isShowDropdown.value = false;
  // 清空搜索框
  searchQuery.value = '';
  // 抛出选中的数据
  
  emit('select', row);
};
</script>

<style lang="scss">
.search-select-container {
  position: relative;
  width: 100%;
}
.heardClassName {
  background-color: #f5f7fa !important; /* 浅蓝色背景 */
}
.table-components .el-table__header-wrapper {
  background-color: #f5f7fa; /* 浅蓝色背景 */
}
.el-input.active .el-input__wrapper {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(var(--el-color-primary-rgb), 0.2);
}

.dropdown-content {
  width: 100%;
  position: absolute;
  top: 40px;
  z-index: 999;
  border: 1px solid #E7E7E7;
  border-radius: 10px;
  overflow: hidden;
}

.no-data {
  text-align: center;
  padding: 16px;
  color: var(--el-text-color-secondary);
}

.el-table {
  width: 100%;
  border-radius: 4px;
}

.el-table__row {
  cursor: pointer;
}
</style>
